package com.link.play.fit.ai.ui.main.fragment.homeFragment

import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.health.connect.client.HealthConnectClient
import androidx.health.connect.client.PermissionController
import androidx.health.connect.client.permission.HealthPermission
import androidx.health.connect.client.records.StepsRecord
import androidx.lifecycle.lifecycleScope
import com.github.mikephil.charting.charts.BarChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.formatter.ValueFormatter
import com.link.play.fit.ai.R
import com.link.play.fit.ai.base.BaseFragment
import com.link.play.fit.ai.bean.UserGuide
import com.link.play.fit.ai.databinding.HomeChildLayout2Binding
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_USER_GUIDE
import com.link.play.fit.ai.utils.HealthUtils.calculateStepCalorieBurn
import com.link.play.fit.ai.utils.HealthUtils.checkPermissionsAndRun
import com.link.play.fit.ai.utils.HealthUtils.getLast7DaysSteps
import com.link.play.fit.ai.utils.HealthUtils.getTodaySteps
import com.link.play.fit.ai.utils.HealthUtils.isSupported
import com.link.play.fit.ai.utils.WeekDatesUtil.getLastSevenDaysPrefixes
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.launch


/**
 *Create by SleepDog on 2025-03-24
 */
class HomeChildFragment2 : BaseFragment<HomeChildLayout2Binding>(HomeChildLayout2Binding::inflate) {

    private val PERMISSIONS by lazy(LazyThreadSafetyMode.NONE) {
        setOf(
//            HealthPermission.getReadPermission(HeartRateRecord::class),
//            HealthPermission.getWritePermission(HeartRateRecord::class),
            HealthPermission.getReadPermission(StepsRecord::class),
//            HealthPermission.getWritePermission(StepsRecord::class)
        )
    }
    private val requestPermissionActivityContract =
        PermissionController.createRequestPermissionResultContract()
    private var healthConnectClient: HealthConnectClient? = null
    private val stepsData by lazy(LazyThreadSafetyMode.NONE) { listOf(0, 0, 0, 0, 0, 0, 0) }
    private var permissionDeniedCount = 0
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initListener()
    }

    override fun lazyInit() {
        initData()
    }

    @SuppressLint("SetTextI18n")
    private fun initData() {
        if (isSupported(requireActivity())) {
            lifecycleScope.launch(exceptionHandler) {
                healthConnectClient = HealthConnectClient.getOrCreate(requireActivity())
                healthConnectClient?.let {
                    binding.connectHealthLayout.isVisible = !checkPermissionsAndRun(it)
                    val userGuide = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
                    userGuide?.let { k ->
                        val kg = userGuide.weightKg
                        val height = userGuide.heightCm
                        val todaySet = getTodaySteps(it)
                        getLast7DaysSteps(System.currentTimeMillis(), it)
                        binding.setValueText.text = "+$todaySet"
                        binding.carbsValueText.text =
                            "${calculateStepCalorieBurn(todaySet, kg.toFloat(), height.toDouble())}"
                    }
                }
            }
        } else {
            binding.connectHealthLayout.isVisible = true
        }
        setupBarChart(binding.barChart)
    }

    private fun initListener() {
        binding.childLayout1.setOnClickListener { }
        binding.carbsLayout.setOnClickListener { }
        binding.connectHealthLayout.setOnClickListener {
            "isSupported(requireActivity() ${isSupported(requireActivity())}".d()
            if (isSupported(requireActivity(), true)) {
                lifecycleScope.launch(exceptionHandler) {
                    val healthConnectClient = HealthConnectClient.getOrCreate(requireActivity())

                    if (checkPermissionsAndRun(healthConnectClient)) {
                        binding.connectHealthLayout.isVisible = false
                    } else {
                        requestPermissions.launch(PERMISSIONS)
                    }
                }
            }
        }
    }

    private val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
        // 处理异常
        "${throwable.printStackTrace()}".d()
    }

//    private val requestPermissions =
//        registerForActivityResult(requestPermissionActivityContract) { granted ->
//            binding.connectHealthLayout.isVisible = !granted.containsAll(PERMISSIONS)
//        }

    private val requestPermissions =
        registerForActivityResult(requestPermissionActivityContract) { granted ->
            val allPermissionsGranted = granted.containsAll(PERMISSIONS)
            binding.connectHealthLayout.isVisible = !allPermissionsGranted
            "allPermissionsGranted $allPermissionsGranted permissionDeniedCount $permissionDeniedCount".d()
            if (!allPermissionsGranted) {
                if (permissionDeniedCount >= 2) {
                    openHealthConnectSettings(requireActivity())
                } else {
                    openHealthSetting()
                }
                permissionDeniedCount++
            }
        }

    private fun openHealthConnectSettings(context: Context) {
        "openHealthConnectSettings ".d()
        try {
            val intent =
                context.packageManager.getLaunchIntentForPackage("com.google.android.apps.healthdata")
            context.startActivity(intent)
        } catch (e: Exception) {
            // 处理未安装的情况
//            Toast.makeText(context, "Health Connect not found", Toast.LENGTH_SHORT).show()
        }
    }

    private fun openHealthSetting() {
        try {
            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                data = Uri.fromParts("package", "com.google.android.apps.healthdata", null)
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
            }
            startActivity(intent)
        } catch (e: ActivityNotFoundException) {
            e.printStackTrace()
            Toast.makeText(context, "Health Connect not installed", Toast.LENGTH_SHORT).show()
        }
    }

    private fun setupBarChart(chart: BarChart) {
        // 1. 基础配置
        chart.apply {
            description.isEnabled = false // 隐藏描述
            legend.isEnabled = false       // 隐藏图例
            setTouchEnabled(false)         // 禁用触摸交互
            setDrawGridBackground(false)   // 隐藏网格背景
            setPinchZoom(false)            // 禁用缩放
        }

        // 2. 准备柱状图数据
        val entries = stepsData.mapIndexed { index, steps ->
            BarEntry(index.toFloat(), steps.toFloat())
        }

        val dataSet = BarDataSet(entries, getString(R.string.Steps)).apply {
            color = Color.parseColor("#17CB81") // 柱状图颜色
            valueTextColor = Color.BLACK        // 数值颜色
            valueTextSize = 11f
            setDrawValues(false)                // 显示柱顶数值
        }

        val barData = BarData(dataSet).apply {
            barWidth = 0.4f // 柱子宽度（0-1之间）
        }
        val weekList = getLastSevenDaysPrefixes()
        // 3. 配置X轴
        chart.xAxis.apply {
            position = XAxis.XAxisPosition.BOTTOM // X轴位置
            granularity = 1f                     // 最小间隔
            setDrawGridLines(false)              // 隐藏网格线
            labelCount = 7                       // 标签数量
            valueFormatter = object : ValueFormatter() {
                override fun getFormattedValue(value: Float): String {
                    return when (value.toInt()) {
                        0 -> weekList[0]
                        1 -> weekList[1]
                        2 -> weekList[2]
                        3 -> weekList[3]
                        4 -> weekList[4]
                        5 -> weekList[5]
                        6 -> weekList[6]
                        else -> weekList[0]
                    }
                }
            }
        }

        // 4. 配置左侧Y轴
        chart.axisLeft.apply {
            axisMinimum = 0f                     // 最小值从0开始
            granularity = 1000f                  // 刻度间隔
            setDrawGridLines(true)               // 显示水平网格线
            gridColor = Color.LTGRAY             // 网格线颜色
            gridLineWidth = 0.5f
            axisLineColor = Color.DKGRAY
        }

        // 5. 隐藏右侧Y轴
        chart.axisRight.isEnabled = false

        // 6. 绑定数据并刷新
        chart.data = barData
        chart.invalidate()
    }

}